package cn.demoframe.test.frame.controller;

import cn.demoframe.test.frame.model.UserInfo;
import cn.demoframe.test.frame.service.UserinfoService;
import cn.demoframe.test.frame.vmodel.UserForm;
import cn.demoframe.test.model.Griddata_pageinfo;
import cn.demoframe.test.model.Message;
import cn.demoframe.test.utils.Constants;
import cn.demoframe.test.utils.CryptToolkit;
import cn.demoframe.test.utils.DateToolkit;
import cn.demoframe.test.utils.Function;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Controller
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(Thread
            .currentThread().getStackTrace()[1].getClassName());

    @Resource(name = "UserinfoServiceImpl")
    private UserinfoService userinfoService;

    @RequestMapping(value = { "/auth/userinfo/getpersonal" }, method = { RequestMethod.POST })
    @ResponseBody
    public UserForm getPersonal(HttpServletRequest request) {
        HttpSession session = request.getSession();
        String userid = (String)session.getAttribute("LOGIN_USER");
        List<UserInfo> list = userinfoService.getUserInfos(null, userid,
                null, null, null, Constants.STATUS_ON, null, null, null);

        UserInfo u = list.get(0);
        UserForm uform = new UserForm();
        uform.setUserid(u.getUserid());
        uform.setUsernm(u.getUsernm());
        uform.setRoleid(u.getRoleid());
        uform.setRolenm(u.getRolenm());
        uform.setEmail(u.getEmail());
        uform.setMobile(u.getMobile());
        uform.setRemark(u.getRemark());
        uform.setLmtserial(u.getLmtserial());
        return uform;
    }

    @RequestMapping(value = { "/auth/userinfo/modpersonal" }, method = { RequestMethod.POST })
    @ResponseBody
    public Message modPersonal_log(HttpServletRequest request,
            @RequestParam(value = "usernm") String usernm,
            @RequestParam(value = "email") String email,
            @RequestParam(value = "mobile") String mobile,
            @RequestParam(value = "remark") String remark) {
        Message m = new Message();
		String userid = request.getSession().getAttribute("LOGIN_USER").toString();
        try {
			userinfoService.modUserInfo(userid, usernm, null,
			        null, email, mobile, remark, Constants.STATUS_ON);
			m.setResult("00");
	        m.setDetail("个人信息修改成功.");
		} catch (Exception e) {
			m.setResult("99");
	        m.setDetail("个人信息修改失败.");
	        logger.error("个人信息修改失败", e);
		}
        return m;
    }
    
    @RequestMapping(value = { "/auth/userinfo/modpasswd" }, method = { RequestMethod.POST })
    @ResponseBody
    public Message modPasswd_log(HttpServletRequest request,
            @RequestParam(value = "oldpasswd") String oldpasswd,
            @RequestParam(value = "newpasswd") String newpasswd) {
        Message m = new Message();

        String userid = request.getSession().getAttribute("LOGIN_USER").toString();
        List<UserInfo> list = userinfoService.getUserInfos(null, userid,
                null, CryptToolkit.getJavaMD5(CryptToolkit.base643DesEncoder(oldpasswd, Constants.ENCRYPTKEY)),
                null, Constants.STATUS_ON, null, null, null);

        if(list.size() == 0){
            m.setResult("99");
            m.setDetail("旧密码不正确.");
            return m;
        }
        try {
			userinfoService.modUserInfo(userid, null,
					CryptToolkit.getJavaMD5(CryptToolkit.base643DesEncoder(newpasswd, Constants.ENCRYPTKEY)), null,
			        null, null,  null, Constants.STATUS_ON);
			m.setResult("00");
			m.setDetail("密码修改成功.");
		} catch (Exception e) {
			m.setResult("99");
			m.setDetail("密码修改失败.");
			logger.error("密码修改失败", e);
		}
        return m;
    }

    /**
     * 根据指定条件分页获取用户信息
     */
    @RequestMapping(value = "/auth/userinfo/userinfos", method = RequestMethod.POST)
    @ResponseBody
    public Griddata_pageinfo getUserinfos(HttpServletRequest request,
    		@RequestParam(value = "page") Integer page,
            @RequestParam(value = "limit") Integer rows) {
        int beginRow = (page - 1) * rows;// ROWNUM从1开始
        int endRow = page * rows;
        String sort = Function.dealNull(request.getParameter("sort"));
        String order = Function.dealNull(request.getParameter("order"));

        logger.debug("根据指定条件分页获取用户信息 - 列表属性↓：\npage:{} rows:{} sort:{} order:{}", page, rows,
                sort, order);

        int total = userinfoService.getUserInfosCount(null, null,
                null, null, Constants.STATUS_ON);

        List<UserInfo> list = userinfoService.getUserInfos(null, null, null,
                null, null, Constants.STATUS_ON, beginRow, endRow, sort + " " + order);

        return new Griddata_pageinfo(total, list);
    }

    @RequestMapping(value = { "/auth/userinfo/userformdetail/{userid}/{type}/{random}" }, method = { RequestMethod.GET })
    @ResponseBody
    public UserForm getFormDetail(@PathVariable("userid") String userid,
            @PathVariable("type") String type) {// URL末尾增加一个随机数，避免缓存。
        logger.debug("获取用户编辑表单明细信息");
        List<UserInfo> list = userinfoService.getUserInfos(null, userid,
                null, null, null, Constants.STATUS_ON, null, null, null);

        UserInfo u = list.get(0);
        UserForm uform = new UserForm();
        if ("edit".equals(type)) {// 编辑
            uform.setUserid(u.getUserid());
            uform.setUsernm(u.getUsernm());
        } else {// 复制copy
            uform.setUserid("");
            uform.setUsernm("");
        }
        uform.setRoleid(u.getRoleid());
        uform.setRolenm(u.getRolenm());
        uform.setEmail(u.getEmail());
        uform.setMobile(u.getMobile());
        uform.setRemark(u.getRemark());
        uform.setLmtserial(u.getLmtserial());
        return uform;
    }

	@RequestMapping(value = { "/auth/userinfo/adduser" }, method = { RequestMethod.POST })
    @ResponseBody
    public Message addUser_log(HttpServletRequest request, HttpEntity<UserForm> model) {
        logger.debug("新增用户");
        Message m = new Message();
        UserForm uf = model.getBody();
        int num = userinfoService.getUserInfosCount(uf.getUserid(),
                null, null, null, Constants.STATUS_ON);
        if (num > 0) {
            m.setResult("99");
            m.setDetail("用户已存在.");
            return m;
        }

        try {
			UserInfo u = new UserInfo();
			u.setUserid(uf.getUserid());
			u.setUsernm(uf.getUsernm());
			u.setMobile(uf.getMobile());
			u.setRoleid(uf.getRoleid());
			u.setEmail(uf.getEmail());
			u.setRemark(uf.getRemark());
            u.setParentid(request.getSession().getAttribute("LOGIN_USER").toString());
            String passwd = Function.genRandomNum(6);
            // 3des base64后再md5存储
			u.setPasswd(CryptToolkit.getJavaMD5(CryptToolkit.base643DesEncoder(passwd, Constants.ENCRYPTKEY)));
            u.setCreatetime(DateToolkit.Date2String(new Date(), DateToolkit.YYYY_MM_DD_HH24_MM_SS));
			userinfoService.addUserInfo(u);
			m.setResult("00");
			m.setDetail("用户新增成功,新用户初始密码为:" + passwd);
		} catch (Exception e) {
			m.setResult("99");
			m.setDetail("用户新增失败.");
			logger.error("用户新增失败", e);
		}
        return m;
    }

    @RequestMapping(value = { "/auth/userinfo/moduser" }, method = { RequestMethod.POST })
    @ResponseBody
    public Message modUser_log(HttpServletRequest request, HttpEntity<UserForm> model) {
        logger.debug("修改用户");
        Message m = new Message();
        UserForm uf = model.getBody();

        try {
			userinfoService.modUserInfo(uf.getUserid(), uf.getUsernm(), null,  uf.getRoleid(), 
			        uf.getEmail(), uf.getMobile(),  uf.getRemark(), Constants.STATUS_ON);
			m.setResult("00");
			m.setDetail("用户信息修改成功.");
		} catch (Exception e) {
			m.setResult("99");
			m.setDetail("用户信息修改失败.");
			logger.error("用户信息修改失败", e);
		}
        return m;
    }

    @RequestMapping(value = { "/auth/userinfo/deluser" }, method = { RequestMethod.POST })
    @ResponseBody
    public Message delUser_log(HttpServletRequest request,
            @RequestParam(value = "userid") String userid) {
        logger.debug("删除用户");
        Message m = new Message();
        userinfoService.delUserInfo(userid);
        m.setResult("00");
        m.setDetail("用户已删除.");
        return m;
    }

}
